package main

import (
	"context"
	"errors"
	"fmt"
	"github.com/asim/go-micro/plugins/registry/etcd/v3"
	"github.com/asim/go-micro/v3"
	"github.com/asim/go-micro/v3/logger"
	"github.com/asim/go-micro/v3/registry"
	"go-learn/test/microTest/pb"
	"google.golang.org/grpc/metadata"
)

type handler struct {
}

func (h *handler) Search(ctx context.Context, in *pb.SearchRequest, out *pb.SearchResponse) error {
	fmt.Println("server被调用了！！！")
	// 获取请求头（实际是一个map集合）
	md, ok := metadata.FromIncomingContext(ctx)
	if ok {
		fmt.Println(md)
	}
	// 模拟数据
	var people pb.People
	switch in.Id {
	case 1:
		people = pb.People{Name: "张三", Male: true, Scores: 60}
	case 2:
		people = pb.People{Name: "李四", Male: true, Scores: 80}
	case 3:
		people = pb.People{Name: "王五", Male: true, Scores: 100}
	default:
		return errors.New("操作失败")
	}
	out.Status = 200
	out.Data = &people
	return nil
}

func main() {
	etcdReg := etcd.NewRegistry(
		registry.Addrs("192.168.197.121:2379"),
	)

	// asim/go-micro 创建服务
	server := micro.NewService(
		micro.Name("test"),
		micro.Registry(etcdReg),
	)

	// Initialize service
	server.Init()

	// Register handler
	pb.RegisterSearchServiceHandler(server.Server(), new(handler))

	// Run service
	if err := server.Run(); err != nil {
		logger.Fatal(err)
	}
}
